/**
 *
 */
package com.edooteach.webpay.helper.impl;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import com.demo2do.core.utils.StringUtils;
import com.edooteach.webpay.helper.SignatureHelper;

/**
 * @author lute
 */
@Component("wechatpaySignatureHelper")
public class WechatpaySigantureHelper implements SignatureHelper {

    private String appKey;

    /**
     * Initialize WeChat APP key
     * @param appKeyPath
     * @throws IOException
     */
    @Autowired
    public void initAppKey(@Value("#{payment['wechat.appKeyPath']}") String appKeyPath) throws IOException {
        Resource resource = new ClassPathResource(appKeyPath);
        this.appKey = FileUtils.readFileToString(resource.getFile(), "UTF-8");
    }

    /* (non-Javadoc)
     * @see com.edooteach.webpay.helper.SignatureHelper#sign(java.util.Map)
     */
    public String sign(Map<String, String> signatureContext) {
        String queryString = StringUtils.toSortedQueryString(signatureContext);
        return DigestUtils.md5Hex(StringUtils.connect(queryString, "&key=", appKey)).toUpperCase();
    }

    /* (non-Javadoc)
     * @see com.edooteach.webpay.helper.SignatureHelper#check(java.lang.String, java.lang.String)
     */
    public boolean validate(String sortedQueryString, String sign) {
        
        String queryString = new StringBuilder().append(sortedQueryString)
                .append("&key=")
                .append(appKey)
                .toString();

        String signature = DigestUtils.md5Hex(queryString).toUpperCase();

        return org.apache.commons.lang3.StringUtils.equals(sign, signature);
        
    }

    /**
     * @return the appKey
     */
    public String getAppKey() {
        return appKey;
    }

}
